<?php
namespace control;

/*
*销售计划文件单类
*/

class saleOrderFileClass extends adIndexClass
{
    private const page = 'saleOrderFile';
    private const title = '销售计划';
    private const target = '销售计划';
    private const targetId = 'ad9c44a9429520f1';//固定ID

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'staff' => [
                'name'  => "上传者",
                'width' => 250,
            ],
            'name'  => [
                'name'  => "附件名称",
                'width' => 300,
                'sort' => 1,
            ],
//            'secret'         => [
//                'name'  => '保密',
//                'width' => 250,
//            ],
            'format'          => [
                'name'  => '类型',
                'width' => 250,
                'sort' => 1,
            ],
            'size'          => [
                'name'  => '体积',
                'width' => 250,
                'sort' => 1,
            ],
            'time'          => [
                'name'  => '上传时间',
                'width' => 250,
                'sort' => 1,
            ]
        ];
        return $tr;
    }
    /*列表页-查询条件*/
    public function homeOptions($fileId,$isAsync = true,)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "对象" => repeatSelect(array('sqlForm' => 'file', 'sqlField' => 'target', 'name' => 'target')),
                    "附件名称"   => text(array("name" => "name")),
                    '上传日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])).hidden(['name'=>'fileId','value'=>$fileId]),
                ],
            ],
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $fileId = self::getId();
        $html = $this->homeOptions($fileId,false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"document.{$fileId}form.img.click()\">添加附件</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' title='勾选并批量删除附件' onclick=\"pasWarn('listForm','file','delete')\">删除所选</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        $fileId = $this->post('fileId');
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//附件名称
        );
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//负责人
        );
        //对象
        $and = "target = '" . self::target . "' and targetId = '" . self::targetId . "'";
        //发生时间-开始日期
        if (!empty($this->post('startDay'))) {
            $startDay = $this->post('startDay') . " 00:00:00";
            $and .= " and time >= '$startDay' ";
        }
        //发生时间-结束日期
        if (!empty($this->post('endDay'))) {
            $endDay = $this->post('endDay') . " 23:59:59";
            $and .= " and time <= '$endDay' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = $and . search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => "file", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll('listForm', "fileId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "fileId", "value" => $array['id']),
                "download" => array("name" => $array['name'], "href" => $array['src']),
            );
            if (in_array($array['format'], array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"))) {
                $dominate['preview'] = array("format" => $array['format'], "name" => $array['name'], "href" => $array['src']);
            } elseif (in_array($array['format'], array("png", "gif", "jpg"))) {
                $dominate['img'] = array("title" => "在线预览", "href" => $array['src']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staff":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "secret":
//                        if ($array['stid'] == $this->control['stid']) {
//                            if ($array['secret'] == "是") {
//                                $secretTitle = "点击调整为否";
//                            } else {
//                                $secretTitle = "点击调整为是";
//                            }
//                            $secret = "<span class='spanButton' title='" . $secretTitle . "' id='" . $array['id'] . "' onclick=\"fileSecret(this)\">" . ($array['secret'] ?: '否') . "</span>";
//                        } else {
                            $secret = $array['secret'] ?: '否';
//                        }
                        $row[] = $secret;
                        break;
                    case "size":
                        $row[] = self::formatSize($array['size']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] =
            "<form name='listForm'>" .
            $li .
            "</form>" .
            \control\machiningOrderClass::closeJs() .
            $page['button'] .
            clear.
        $this->uploadHtml(self::target, self::targetId, $fileId, $this->root . 'control/adIndex.html?cla=file&fun=chunkUpload') .
        $this->dragUploadHtml(self::target, self::targetId, $this->root . 'control/adIndex.html?cla=file&fun=chunkUpload', 'body');
        return json_encode($json, 320);
    }

    /**
     * Desc : 显示上传控件
     * User : you name
     * Date : 2024-02-22 11:45
     * @param $target
     * @param $targetId
     * @param $fileId
     * @param $url
     * @return string
     */
    public function uploadHtml($target, $targetId, $fileId, $url)
    {
        $formName = $fileId . 'form';
        return '
            <div class="hide">
                <form name="' . $formName . '" method="post" enctype="multipart/form-data">
                    <input name="img" type="file" multiple onchange="choiceFileUpload(this, \'' . $target . '\', \'' . $targetId . '\', \'' . $url . '\')">
                    <input name="target" type="hidden" value="' . $target . '">
                    <input name="targetId" type="hidden" value="' . $targetId . '">
                </form>
            </div>' .
            "<script>
                function choiceFileUpload(e, target, targetId, url) {
                    var fileList = $(e).prop('files'); //获取文件对象
                    var arr = [];
                    const chunkSize = 5 * 1024 * 1024;
                    $.each(fileList,function(n,file){
                        var value = {
                            'code':  CryptoJS.MD5(file.name + file.size + file.lastModified).toString(),
                            'target':  target,
                            'name':  file.name,
                            'size':  file.size,
                            'target_id':  targetId,
                            'chunks':  Math.ceil(file.size / chunkSize),
                            'power':  'share',
                            'error':  '',
                        }
                        arr.push(value)
                    });
                    $.post(root + 'control/adIndex.html?cla=share&fun=checkUpload', {fileInfo:JSON.stringify(arr)}, function (res) {
                        if(res.warn === 2){
                            layer('share', 'uploadList', {'fileInfo': res.data, 'notClose': 1  })
                            //分片上传
                            for (var i = 0; i < res.data.length; i++) {
                                uploadChunks(fileList[i], res.data[i], url)
                            }
                        }else{
                            msg(res.warn, 'error')
                        }
                    }, 'json')
                }
            </script>";
    }

    /**
     * Desc : 拖拽上传
     * User : you name
     * Date : 2024-02-21 09:38
     * @param $target
     * @param $targetId
     * @param $url
     * @param $node
     * @return string
     */
    public function dragUploadHtml($target, $targetId, $url, $node)
    {
        return "
    <div id='windowMaskView' class='maskView'></div>
    <div id='maskViewContent' class='viewContent'>
        <div class='content-div'>
            <div class='upload-tips'>						
                <div class='cloud-icon'>							
                    <i class='icon-cloud cloud1 moveLeftLoop'></i>
                    <i class='icon-cloud cloud2'></i>
                    <i class='icon-cloud cloud3 moveLeftLoop'></i>
                </div>
                <div class='cloud-moveup'>
                    <i class='moveTopLoop icon-circle-arrow-up'></i>
                </div>						
                <div class='msg'>松开即可上传!</div>
            </div>
        </div>
    </div>
    <script>
        var target = '{$target}'
        var targetId = '{$targetId}'
        var url = '{$url}'
        var node = '{$node}'
        $(document).ready(function(){
            let elemetnNode=''//最后一次节点
            //要想实现拖拽，首页需要阻止浏览器默认行为，一个四个事件。
            $('#'+node).on({
                dragleave:function(e){		//拖离
                    e.preventDefault();     //移除原有浏览器监听效果
                    if(elemetnNode===e.target)
                    $('.maskView,.viewContent').removeClass('over');
                },
                drop:function(e){			//拖后放
                    e.preventDefault();     //移除原有浏览器监听效果
                },
                dragenter:function(e){		//拖进
                    elemetnNode=e.target;
                    e.preventDefault();     //移除原有浏览器监听效果
                    $('.maskView,.viewContent').addClass('over');
                },
                dragover:function(e){		//拖来拖去
                    e.preventDefault();     //移除原有浏览器监听效果
                    $('.maskView,.viewContent').addClass('over');
                }
            });
            
            //================上传的实现
            var box = document.getElementById(node); //获得到框体
            var newHandle = function(e){
                e.preventDefault(); //取消默认浏览器拖拽效果
                e.stopPropagation()
                var fileList = e.dataTransfer.files; //获取文件对象
                //fileList.length 用来获取文件的长度（其实是获得文件数量）
                console.log(fileList)
                
                //检测是否是拖拽文件到页面的操作
                if(fileList.length == 0){
                    $('.maskView,.viewContent').removeClass('over');
                    return;
                }
                var arr = [];
                const chunkSize = 5 * 1024 * 1024;
                $.each(fileList,function(n,file){
                    var value = {
                        'code':  CryptoJS.MD5(file.name + file.size + file.lastModified).toString(),
                        'target':  target,
                        'name':  file.name,
                        'size':  file.size,
                        'target_id':  targetId,
                        'chunks':  Math.ceil(file.size / chunkSize),
                        'power':  'share',
                        'error':  '',
                    }
                    arr.push(value)
                });
                $.post(root + 'control/adIndex.html?cla=share&fun=checkUpload', {fileInfo:JSON.stringify(arr)}, function (res) {
                    $('.maskView,.viewContent').removeClass('over');
                    if(res.warn === 2){
                        layer('share', 'uploadList', {'fileInfo': res.data, 'notClose': 1 })
                        //分片上传
                        for (var i = 0; i < res.data.length; i++) {
                            uploadChunks(fileList[i], res.data[i], url)
                        }
                        box.removeEventListener(\"drop\",newHandle);
                    }else{
                        msg(res.warn, 'error')
                    }
                }, 'json')
            }
            box.addEventListener(\"drop\",newHandle,false);
        });
            
    </script>";
    }

}
